<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>登录示例</title>
</head>
<body>
  <form action="#" method="get" onsubmit="return validateForm()">
    <table border="1" cellspacing="0" cellpadding="5" align="center">
      <caption><h3>登录</h3></caption>
      <tr>
        <td>姓 名</td>
        <td>
          <input id="name" name="username" type="text" placeholder="请输入姓名" onblur="validateName()">
          <span id="nameMsg"></span>
        </td>
      </tr>
      <tr>
        <td>密 码</td>
        <td>
          <input id="password" name="password" type="password" placeholder="请输入密码" onblur="validatePassword()">
          <span id="passwordMsg"></span>
        </td>
      </tr>
      <tr align="center">
        <td colspan="2">
          <input type="submit" value="登录">
          <input type="reset" value="重置" onclick="clearMsgs()">
        </td>
      </tr>
    </table>
  </form>

  <script>
    function validateName() {
      var name = document.getElementById("name").value.trim();
      var msg = document.getElementById("nameMsg");
      var reg = /^[\u4e00-\u9fa5A-Za-z0-9_]+$/;

      if (name == "") {
        msg.innerHTML = "<font style='color:red'>姓名不能为空</font>";
        return false;
      }
      if (!reg.test(name)) {
        msg.innerHTML = "<font style='color:red'>姓名中含有非法字符</font>";
        return false;
      }
      msg.innerHTML = "<font style='color:green'>姓名通过</font>";
      return true;
    }

    function validatePassword() {
      let pwd = document.getElementById("password").value;
      let msg = document.getElementById("passwordMsg");
      let count = 0;

      if (/[0-9]/.test(pwd)) count++;
      if (/[a-z A-Z]/.test(pwd)) count++;
      if (/[!@#\$%\^&\*]/.test(pwd)) count++;

      if (count <= 1) {
        msg.innerHTML = "<font style='color:red'>密码强度：弱</font>";
        return false;
      } else if (count <= 2) {
        msg.innerHTML = "<font style='color:orange'>密码强度：中</font>";
        return true;
      } else {
        msg.innerHTML = "<font style='color:green'>密码强度：强</font>";
        return true;
      }
    }

    function validateForm() {
     let okName = validateName();
     let okPwd = validatePassword();
      return okName && okPwd;
    }

    function clearMsgs() {
      document.getElementById("nameMsg").innerHTML = "";
      document.getElementById("passwordMsg").innerHTML = "";
    }
  </script>
</body>
</html>
